/* 

   Opgave 2

   redirect.c

 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

#include "redirect.h"

int redirect_stdincmd(char *filename, char *argv[], char *infilename)
{
  pid_t pid = fork(); //spawning child process

	if(pid == 0) {
		int fid = open(infilename, O_RDONLY); //open file readOnly mode
		close(0); //closing stdin 0 = stdin
		dup(fid); //replacing stdin with fid
		execvp(filename, argv); //executing the statements
		close(fid); //closing fid
	}
	else {
	     int status;
	     waitpid(pid,&status,0); //waiting for the child process to finish
	}
}

int redirect_stdoutcmd(char *filename, char *argv[], char *outfilename)
{
  	pid_t pid = fork (); //spawning child process

	  if(pid == 0) {
		//opening new file for output
		int fid = open(outfilename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IROTH | S_IRGRP);
		close(1); //closing stdout 1 = stdout
		dup(fid); //replacing stdout with fid
		execvp(filename, argv); //executing the statements
		close(fid); //closing fid
	  }
	  else {
		int status; 
		waitpid(pid,&status,0);	//waiting for the child process to finish
	  }
}
